package pres.wchen.bussiness.cor.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 源文件名：HttpClientUtils.java
 * 文件版本：1.0.0
 * 创建作者：wchen
 * 创建日期：2017/9/22
 * 文件描述：http 模拟工具类
 * 版权所有：Copyright 2017, Inc. All Rights Reserved.
 */
public class HttpClientManager {

    static CloseableHttpClient httpClient = null;

    public static synchronized CloseableHttpClient getHttpClient() {

        if (httpClient == null) {
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            // 连接池最大连接数
            cm.setMaxTotal(200);
            // 单条链路最大连接数（一个ip+一个端口 是一个链路）
            cm.setDefaultMaxPerRoute(100);
            // 指定某条链路的最大连接数
            ConnectionKeepAliveStrategy kaStrategy = new DefaultConnectionKeepAliveStrategy();
            httpClient = HttpClients.custom().setConnectionManager(cm).setKeepAliveStrategy(kaStrategy).build();
        }

        return httpClient;
    }


    /**
     * @方法描述
     * @创建作者 wchen
     * @方法入参 模拟http post 请求
     * @返回值
     * @创建日期 2017/9/22
     */
    public static void post(String url, Map map) {

        System.out.println("================  URL is : "+ url+" ================");

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        Iterator it = map.keySet().iterator();
        while (it.hasNext()){
            Object key = it.next();
            formparams.add(new BasicNameValuePair(key.toString(), map.get(key).toString()));

        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @方法描述
     * @创建作者 wchen
     * @方法入参 模拟http get请求
     * @返回值
     * @创建日期 2017/9/22
     */
    public static JSONObject doGet(String url, Map map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            StringBuffer sbf = new StringBuffer(url).append("?");
            Iterator it = map.keySet().iterator();
            while (it.hasNext()){
                Object key = it.next();
               sbf.append(key).append("=").append(map.get(key)).append("&");
            }
            String getUrl = sbf.substring(0,sbf.length()-1);

            // 创建httpget
            HttpGet httpget = new HttpGet(getUrl);
//            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
//                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
//                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
                System.out.println("------------------------------------");

                return JSONObject.parseObject(EntityUtils.toString(entity));
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @方法描述 post json格式
     * @创建作者 wchen
     * @方法入参
     * @返回值
     * @创建日期 2017/9/23
     */
    public static void doPost(String url,Object json){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(),"utf-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            //header
            post.setHeader("Cookie", "JSESSIONID=EC01768FAA86786AE740E094030E2AF9");

            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
//                response = JSONObject.fromObject(result);
                System.out.println("Response content: " + result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}